﻿using log4net;
using OdsServer.Common;
using OdsServer.Common.Utils;
using OdsServer.DataTransfer;
using StructureMap;

namespace OdsServer
{
    public sealed class OdsServerService : IServerService
    {
        private static readonly ILog log                        = LogManager.GetLogger(typeof(OdsServerService));
        private ITransferService transferService                = null;
        private IDeviceHandler device                           = null;
        private SetupParamChangedCallback OnSetupParamChange    = null;
        private SetupParameters parameters;

        public OdsServerService(ITransferService transferService, IDeviceHandler deviceHandler)
        {
            this.transferService    = transferService;
            this.device             = deviceHandler;
            this.device.ProcessingCallback = new DeviceDataCallback(transferService.ProcessData);

            this.OnSetupParamChange += this.transferService.SetupParamChangedCallback;
            this.OnSetupParamChange += this.device.SetupParamChangedCallback;
        }

        public SetupParameters SetupParameters
        {
            get { return this.parameters; }

            set
            {
                lock (this)
                {
                    if (!ValidationUtils.ValidateSetupParameters(value))
                        throw new OdsServerException("Setup parameters incorrect.");

                    this.parameters = value;

                    // force change notification
                    if (this.OnSetupParamChange != null)
                        this.OnSetupParamChange(this.parameters);
                }
            }
        }

        public void Start()
        {
            lock (this)
            {
                this.transferService.Start();

                this.device.Start();
            }
        }

        public void Stop()
        {
            lock (this)
            {
                this.transferService.Stop();

                this.device.Stop();
            }
        }

        private void ValidateParameters()
        {
            if (!ValidationUtils.ValidateSetupParameters(this.parameters))
                throw new OdsServerException("Setup parameters incorrect.");
        }
    }
}